import React from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Alert, Divider, Select, message, Upload } from 'antd';
import router from 'umi/router';
import { digitUppercase } from '@/utils/utils';
import styles from './style.less';

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

@connect(({ createdForm, loading }) => ({
  submitting: loading.effects['createdForm/submitStepForm'],
  createdForm,
}))
@Form.create()
class Step4 extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      businessLicenseList: [],
      legalCardList: [],
      bankPermissionList: [],
      managerCardList: [],
      fddApplyChartList: [],
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    let enterpriseDetail = localStorage.getItem('enterpriseDetail');
    dispatch({
      type: 'createdForm/fetchBankList',
    });
    let step4 = localStorage.getItem('step4');
    if (step4) {
      this.setState({
        data: JSON.parse(step4),
      });
    } else if (enterpriseDetail) {
      this.setState({
        data: JSON.parse(enterpriseDetail),
      });
    }
  }

  customRequest = (componentsData, type) => {
    let _this = this;
    const { dispatch, form } = this.props;
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    formData.append('dir', 'data');
    dispatch({
      type: 'global/upload',
      payload: formData,
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          _this.setState({
            [type]: res.msg.url,
          });
          form.setFieldsValue({
            [type]: res.msg.url,
          });
          _this.handleChange(type, [obj]);
        }
      },
    });
  };
  handleChange = (type, info) => {
    let logoList = info;
    logoList = logoList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });

    logoList = logoList.filter(file => {
      if (file.response) {
        return file.response.status === 'success';
      }
      return true;
    });

    if (type === 'businessLicense') {
      this.setState({ businessLicenseList: logoList });
    } else if (type === 'legalCard') {
      this.setState({ legalCardList: logoList });
    } else if (type === 'bankPermission') {
      this.setState({ bankPermissionList: logoList });
    } else if (type === 'managerCard') {
      this.setState({ managerCardList: logoList });
    } else if (type === 'fddApplyChart') {
      this.setState({ fddApplyChartList: logoList });
    }
  };

  render() {
    const { form, dispatch, submitting } = this.props;
    const { validateFields } = form;
    const { data } = this.state;

    const {
      location: { query },
    } = this.props;
    const {
      businessLicenseList,
      legalCardList,
      bankPermissionList,
      managerCardList,
      fddApplyChartList,
    } = this.state;

    const onPrev = () => {
      router.push({
        pathname: '/preloan/enterprise/create/step3',
        query: query,
      });
    };

    const onNext = e => {
      e.preventDefault();
      validateFields((err, values) => {
        console.log(this.state.legalCard);
        values.legalCard =
          this.state.legalCard === undefined ? data.legalCard : this.state.legalCard;
        values.managerCard =
          this.state.managerCard === undefined ? data.managerCard : this.state.managerCard;
        values.bankPermission =
          this.state.bankPermission === undefined ? data.bankPermission : this.state.bankPermission;
        values.businessLicense =
          this.state.businessLicense === undefined
            ? data.businessLicense
            : this.state.businessLicense;
        values.fddApplyChart =
          this.state.fddApplyChart === undefined ? data.fddApplyChart : this.state.fddApplyChart;

        console.log(values);
        if (!err) {
          let step1 = JSON.parse(localStorage.getItem('step1'));
          let step2 = JSON.parse(localStorage.getItem('step2'));
          let step3 = JSON.parse(localStorage.getItem('step3'));
          let enterpriseDetail = localStorage.getItem('enterpriseDetail');
          let types = 'createdForm/submitStepForm';
          if (enterpriseDetail) {
            step1.enterpriseNo = JSON.parse(enterpriseDetail).enterpriseNo;
            types = 'createdForm/submitStepEdit';
          }

          dispatch({
            type: types,
            payload: {
              ...step1,
              ...step2,
              ...step3,
              ...values,
            },
            callback(res) {
              if (res.code === 200) {
                localStorage.setItem('step-res', JSON.stringify(res.msg));
                localStorage.removeItem('step1');
                localStorage.removeItem('step2');
                localStorage.removeItem('step3');
                localStorage.removeItem('step4');
                localStorage.removeItem('enterpriseDetail');
                router.push('/preloan/enterprise/create/step5');
              } else {
                message.error(res.errMsg);
              }
            },
          });
        }
      });
    };

    const uploadProps = {
      action: `/img/upload`,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: false },
      multiple: false,
      listType: 'picture-card',
      className: 'upload-list-inline',
    };

    const customRequest1 = {
      ...uploadProps,
      customRequest: event => this.customRequest(event, 'legalCard'),
    };
    const customRequest2 = {
      ...uploadProps,
      customRequest: event => this.customRequest(event, 'managerCard'),
    };
    const customRequest3 = {
      ...uploadProps,
      customRequest: event => this.customRequest(event, 'bankPermission'),
    };
    const customRequest4 = {
      ...uploadProps,
      customRequest: event => this.customRequest(event, 'businessLicense'),
    };
    const customRequest5 = {
      ...uploadProps,
      customRequest: event => this.customRequest(event, 'fddApplyChart'),
    };

    return (
      <Form layout="horizontal" className={styles.stepForm}>
        <Form.Item {...formItemLayout} label="法人证件照" required={false}>
          {legalCardList.length > 0
            ? form.getFieldDecorator('legalCard', {
                rules: [{ required: true, message: '请上传法人证件照！' }],
              })(
                <Upload {...customRequest1} fileList={legalCardList}>
                  法人证件照
                </Upload>
              )
            : form.getFieldDecorator('legalCard', {
                rules: [{ required: false, message: '请上传法人证件照！' }],
              })(
                <Upload
                  {...customRequest1}
                  fileList={
                    data.legalCard
                      ? [
                          {
                            name: data.legalCard,
                            uid: 1,
                            url: data.legalCard,
                          },
                        ]
                      : []
                  }
                >
                  法人证件照
                </Upload>
              )}
        </Form.Item>
        <Form.Item {...formItemLayout} label="管理员证件照" required={false}>
          {managerCardList.length > 0
            ? form.getFieldDecorator('managerCard', {
                rules: [{ required: true, message: '请上传管理员证件照！' }],
              })(
                <Upload {...customRequest2} fileList={managerCardList}>
                  管理员证件照
                </Upload>
              )
            : form.getFieldDecorator('managerCard', {
                rules: [{ required: false, message: '请上传管理员证件照！' }],
              })(
                <Upload
                  {...customRequest2}
                  fileList={
                    data.managerCard
                      ? [
                          {
                            name: data.managerCard,
                            uid: 1,
                            url: data.managerCard,
                          },
                        ]
                      : []
                  }
                >
                  管理员证件照
                </Upload>
              )}
        </Form.Item>
        <Form.Item {...formItemLayout} label="开户许可证" required={false}>
          {bankPermissionList.length > 0
            ? form.getFieldDecorator('bankPermission', {
                rules: [{ required: true, message: '请上传开户许可证！' }],
              })(
                <Upload {...customRequest3} fileList={bankPermissionList}>
                  开户许可证
                </Upload>
              )
            : form.getFieldDecorator('bankPermission', {
                rules: [{ required: false, message: '请上传开户许可证！' }],
              })(
                <Upload
                  {...customRequest3}
                  fileList={
                    data.bankPermission
                      ? [
                          {
                            name: data.bankPermission,
                            uid: 1,
                            url: data.bankPermission,
                          },
                        ]
                      : []
                  }
                >
                  开户许可证
                </Upload>
              )}
        </Form.Item>
        <Form.Item {...formItemLayout} label="营业执照" required={false}>
          {businessLicenseList.length > 0
            ? form.getFieldDecorator('businessLicense', {
                rules: [{ required: true, message: '请上传营业执照！' }],
              })(
                <Upload {...customRequest4} fileList={businessLicenseList}>
                  营业执照
                </Upload>
              )
            : form.getFieldDecorator('businessLicense', {
                rules: [{ required: false, message: '请上传营业执照！' }],
              })(
                <Upload
                  {...customRequest4}
                  fileList={
                    data.businessLicense
                      ? [
                          {
                            name: data.businessLicense,
                            uid: 1,
                            url: data.businessLicense,
                          },
                        ]
                      : []
                  }
                >
                  营业执照
                </Upload>
              )}
        </Form.Item>
        <Form.Item {...formItemLayout} label="法大大申请表" required={false}>
          {fddApplyChartList.length > 0
            ? form.getFieldDecorator('fddApplyChart', {
                rules: [{ required: true, message: '请上传法大大申请表！' }],
              })(
                <Upload {...customRequest5} fileList={fddApplyChartList}>
                  法大大申请表
                </Upload>
              )
            : form.getFieldDecorator('fddApplyChart', {
                rules: [{ required: false, message: '请上传法大大申请表！' }],
              })(
                <Upload
                  {...customRequest5}
                  fileList={
                    data.fddApplyChart
                      ? [
                          {
                            name: data.fddApplyChart,
                            uid: 1,
                            url: data.fddApplyChart,
                          },
                        ]
                      : []
                  }
                >
                  法大大申请表
                </Upload>
              )}
        </Form.Item>

        <Form.Item
          style={{ marginBottom: 8 }}
          wrapperCol={{
            xs: { span: 24, offset: 0 },
            sm: {
              span: formItemLayout.wrapperCol.span,
              offset: formItemLayout.labelCol.span,
            },
          }}
          label=""
        >
          <Button onClick={onPrev}>上一步</Button>
          <Button type="primary" onClick={onNext} loading={submitting} style={{ marginLeft: 8 }}>
            下一步
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

export default Step4;
